var id = getUrlString('id');
var markid = getUrlString('markid');//'3b70887e5d841ff8ab7388ea5f41a5af'
var ipAddress;
var search;
$(function () {
    //分享四要素



        //投票贴详情
    function voteDetail() {
        getData('post','/niu/apiv3/vote_article.php',{'id':id},function (data) {
            console.log(data);
            if(data.resultcode === '0' ){
                var endTime = data.data.endtime;
                $('#totalcount').html(data.data.totalcount);
                $('#optioncount').html(data.data.optioncount);
                $('.poster').css({
                    'background-image': 'url('+data.data.picurl+')',
                    'background-size': 'cover',
                    'background-repeat-x': 'no-repeat',
                    'background-repeat-y': 'no-repeat'
                });
                var intro = data.data.intro;
                $('#intro').html(escape2Html(intro));

                var dateEnd = new Date();//获取当前时间
                var datetime=dateEnd.getFullYear().toString()  + (zeroFill(dateEnd.getMonth() + 1)).toString() + zeroFill(dateEnd.getDate()).toString() +
                    zeroFill(dateEnd.getHours()).toString()  + zeroFill(dateEnd.getMinutes()).toString()  + zeroFill(dateEnd.getSeconds()).toString();
                $('#countDown').html('投票结束倒计时：'+getYMDHMS(datetime,endTime));

                //投票分享
                var titleShare = data.data.title;
                var picUrl = data.data.picurl;
                var introShare = data.data.sharetext;
                var url = 'http://api.odancool.com/niu/html5/wxapp_targeturl.php?url='+urlView+'vote/wechatVote.html?type='+id;
                nativeCommand2(titleShare,picUrl,introShare,url);
            }else {
                laymsg(data.msg)
            }
        })
    }
    voteDetail();

    //投票贴列表
    function voteList(sort) {
        layLoading();
        var data = {
            'id':id,
            'sort':sort,
            'search':search
        };
        getData('post','/niu/apiv3/vote_options.php',data,function (data) {
            console.log(data);
            layer.closeAll('loading');
            if(data.resultcode === '0' ){
                if(data.pagesize === '0'){
                    $('#voteList').empty().hide();
                    $('.noData').show();
                }else {
                    $('.noData').hide();
                    var append = '';
                    $(data.data).each(function () {
                        append += '<li>' +
                            '                <div class="pic">' +
                            '                    <img src="'+ this.picurl +'" alt="">' +
                            '                    <div class="dayNum">'+this.id+'</div>' +
                            '                </div>' +
                            '                <div class="name">'+this.title+'</div>' +
                            '                <div class="voteNum"><span>'+this.totalcount+'</span>票</div>' +
                            '                <div class="voteBtn">投票</div>' +
                            '                <input type="hidden" value="'+ this.id +'"> '+
                            '            </li>'
                    });
                    $('#voteList').empty().append(append).show();
                    $('#voteList .voteBtn').click(function () {
                        var opid = $(this).next('input').val();
                        var voteNum = $(this).prev('.voteNum').find('span').html();
                        var _this = $(this);
                        if(ipAddress == undefined || ipAddress == ''){
                            ipAddress = '0.0.0.0'
                        }
                        var data = {
                            'markid':markid,
                            'aid':id,
                            'opid':opid  ,
                            'ip': ipAddress,
                            'fromtag':'wx',
                        };
                        getData('post','/niu/apiv3/vote_dovote.php',data,function (data) {
                            console.log(data);
                            if(data.resultcode === '0' ){
                                laymsg('投票成功');
                                voteNum ++;
                                _this.prev('.voteNum').find('span').html(voteNum);
                                // _this.html('已投票')
                            }else {
                                laymsg(data.msg)
                            }
                        })
                    })
                }

            }else {
                laymsg(data.msg)
            }
        })
    }

    //默认调用最新投票列表
    voteList(2);





    //判断是否投过票
    function isVote() {
        getData('post','/niu/apiv3/vote_isvote.php',{'markid':markid,'aid':id},function (data) {
            console.log(data);
            if(data.resultcode === '0' ){

            }else {
                laymsg(data.msg)
            }
        })
    }
    // isVote();

    //切换人气投票贴列表
    $('.caseBoxBtn').click(function () {
        $('.tabSwitch li span').removeClass('active');
        $(this).find('span').addClass('active');
        voteList(1);
    });

    //切换最新投票贴列表
    $('.communityBtn').click(function () {
        $('.tabSwitch li span').removeClass('active');
        $(this).find('span').addClass('active');
        voteList(2);
    });

    //搜索
    $('.searchBtn').click(function () {
        search = $('#searchInput').val();
        voteList(2);
    });

    function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
        //compatibility for firefox and chrome
        var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        var pc = new myPeerConnection({
                iceServers: []
            }),
            noop = function() {},
            localIPs = {},
            ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
            key;

        function iterateIP(ip) {
            if (!localIPs[ip]) onNewIP(ip);
            localIPs[ip] = true;
        }

        //create a bogus data channel
        pc.createDataChannel("");

        // create offer and set local description
        pc.createOffer().then(function(sdp) {
            sdp.sdp.split('\n').forEach(function(line) {
                if (line.indexOf('candidate') < 0) return;
                line.match(ipRegex).forEach(iterateIP);
            });

            pc.setLocalDescription(sdp, noop, noop);
        }).catch(function(reason) {
            // An error occurred, so handle the failure to connect
        });

        //sten for candidate events
        pc.onicecandidate = function(ice) {
            if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
            ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
        };
    }
    //获取本机Ip
    getUserIP(function(ip){
        ipAddress = ip
    });





    //分享
    function nativeCommand2(title,picurl,intro,url) {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isiOS) {
            window.webkit.messageHandlers.sharebutton.postMessage(title+"<ika>"+picurl+"<ika>"+intro+"<ika>"+url);
        }else {title,picurl,intro,url
            ikags.sharebutton(title,picurl,intro,url);
        }
    }
});